import { ADD_TODO, REMOVE_TODO, SET_DOING, SET_STATUS, SET_TODOLIST, } from "@/store/actionsType";
import { ITodoItem, TodoStatus } from "@/typings"
import { useStore, Store } from "vuex"
import { watch } from "vue";

export interface IUseTodo {
  AddTodo: (content: string) => void;
  SetTodoList: () => void;
  RemoveTodo: (id: number) => void;
  SetDoing: (id: number) => void;
  SetStatus: (id: number) => void;
}

export function TodoManager(): IUseTodo {

  const store: Store<any> = useStore();
  const { getLocalStrage, setLocalStrage } = useLocalStrage();
  const list = getLocalStrage();

  // watch(() => {
  //   return store.state.list;
  // }, (todoList) => {
  //   setLocalStrage(todoList);
  // })

  function AddTodo(content: string): void {
    const item: ITodoItem = {
      id: new Date().getTime(),
      content,
      status: TodoStatus.WILLDO
    }
    store.dispatch(ADD_TODO, item);
    setLocalStrage(store.state.list);
  }
  function SetTodoList() {
    store.dispatch(SET_TODOLIST, list);
  }
  function RemoveTodo(id: number) {
    store.dispatch(REMOVE_TODO, id);
    setLocalStrage(store.state.list);
  }
  function SetStatus(id: number) {
    store.dispatch(SET_STATUS, id);
    setLocalStrage(store.state.list);
  }
  function SetDoing(id: number) {
    store.dispatch(SET_DOING, id);
    setLocalStrage(store.state.list);
  }
  return {
    AddTodo, SetTodoList, RemoveTodo, SetStatus, SetDoing
  }
}

interface IUseLocalStrage {
  getLocalStrage: () => ITodoItem[];
  setLocalStrage: (list: ITodoItem[]) => void;
}

function useLocalStrage(): IUseLocalStrage {
  function getLocalStrage(): ITodoItem[] {
    return JSON.parse(localStorage.getItem('TodoList') || '[]');
  }
  function setLocalStrage(list: ITodoItem[]): void {
    localStorage.setItem('TodoList', JSON.stringify(list))
  }
  return {
    getLocalStrage, setLocalStrage
  }
}